package cn.izeno.wx.web

import cn.izeno.wx.models.web.BatchContactParam
import cn.izeno.wx.models.web.ChatRoomParam
import cn.izeno.wx.models.web.Member
import cn.izeno.wx.service.Web
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.logging.Logger

object ContactManager {
  private val logger = Logger.getLogger("cn.izeno.wx.web.ContactManager")
  val contact = ArrayList<Member>()

  init {
    MessageReceiver.contactSubject.subscribe { new ->
      val current = contact.find { it.username == new.username }
      if (current != null) {
        contact.remove(current)
      }
      contact.add(new)

      if (new.username.startsWith("@@")) syncChatRoom(new.username)
    }

    // 维护群名称
    MessageReceiver.sysMsg.filter { it.content.contains(Regex("\"([^\"]+)\"修改群名为“([^”]+”)")) }
        .subscribe { msg ->
          try {
            val room = contact.find { member -> member.username == msg.fromUserName }
            if (room != null) {
              val old = room.nickname
              room.nickname = msg.content.split("修改群名为“")[1].replace("”", "")
              logger.info("修改群名称: $old -> ${room.nickname}")
            }
          } catch (e: Exception) {
            logger.warning("更新群名称失败: " + e.message)
          }
        }
  }

  fun sync() {
    getContact()
  }

  fun getContactName(username: String, roomUsername: String? = null): String {
    return if (roomUsername != null) {
      contact.find { it.username == roomUsername }?.memberList
    } else {
      contact
    }?.find { it.username == username }?.nickname ?: ""
  }

  /**
   * [username] 是否在 [roomUsername] 群里
   */
  fun inChatRoom(username: String, roomUsername: String): Boolean {
    return contact
        .find { it.username == roomUsername }
        ?.memberList?.find { it.username == username } != null
  }


  private fun getContact() {
    logger.info("获取联系人")
    Web.service.getContact()
        .subscribeOn(Schedulers.io())
        .subscribe {
          if (it.base.ret == 1101) {
            logger.warning("获取联系人失败，其他地方登录")

          } else {
            contact.addAll(it.data)
            logger.info("收到联系人: " + it.count)
            if (it.base.ret == 1) {
              // 还未获取完联系人
              getContact()
            } else {
              getChatRoomInfo()
            }
          }
        }
  }

  private fun getChatRoomInfo() {
    syncChatRoom(*contact.filter { it.username.startsWith("@@") }.map { it.username }.toTypedArray())
  }

  fun syncChatRoom(vararg username: String) {
    val rooms = username.map { ChatRoomParam(it) }
    val body = BatchContactParam(rooms)
    Web.service.batchContact(body = body)
        .subscribeOn(Schedulers.io())
        .subscribe {
          if (it.base.ret == 0) {
            val roomsName = it.data.map { it.username }.joinToString { "," }
            contact.removeAll(contact.filter { roomsName.indexOf(it.username) != -1 })
            contact.addAll(it.data)
          }
        }
  }
}